//
//  SWConfigManager.swift
//  MiU
//  配置中心
//  Created by linhan on 16/5/7.
//  Copyright © 2016年 MiU. All rights reserved.
//

import Foundation

private let _configManager = SWConfigManager()

let SWConfigManagerConfigChangedNotification:String = "SWConfigManagerConfigChangedNotification"

class SWConfigManager: NSObject,SWAPIComponent
{
    //var mainThreadResumeCallback:(()->Void)?
    var events:[SWKidEvent] = []
    var stages:[SWStage] = []
    var currentStageID:String = ""
    
    //固定在包里的配置参数
    private var _presetParams:[AnyHashable:Any] = [:]
    
    //线上加载的配置参数
    private var _mainParams:[AnyHashable:Any] = [:]
    
    private var _mainThreadResumed:Bool = false
    //启动时的时间
    private var _launchTime:Double = 0
    //var launchADInfo:SWMLaunchInfo?
    
    
    private let semaphore = DispatchSemaphore(value: 0)
    private let ConfigQueue = DispatchQueue(label: "SWConfigManager", attributes: .concurrent)
    
    class func sharedManager() -> SWConfigManager
    {
        return _configManager
    }
    
    override init()
    {
        super.init()
        
        trace("SWConfigManager Init")
        
        //NotificationCenter.default.addObserver(self, selector: #selector(UMOnlineConfigFinish), name: UMOnlineConfigDidFinishedNotification, object: nil)
    }
    
    func launch(options:[UIApplicationLaunchOptionsKey: Any]?, mainThreadSleepWhenLaunch:Bool)
    {
        _launchTime = NSDate().timeIntervalSince1970
        
        if mainThreadSleepWhenLaunch
        {
            DispatchQueue.globalDefault.async(execute: {
                sleep(1)
                self.mainThreadResume()
            })
        }
        
        //先加载本地缓存配置，再对比本地线上配置版本号，需要再拉取
        ConfigQueue.async {
            
            SWNetworkMonitor.sharedMonitor().setup(hostName: nil)
            
            self.getLaunchADInfo()
            self.loadPresetConfig()
            self.loadOpenURLMapList()
            //TODO 接口暂时故障
            self.tokenAvailabilityCheck()
            
        }
        
        if mainThreadSleepWhenLaunch
        {
            //阻塞主线程,等待基本配置数据、启动页数据加载完成
            semaphore.wait(timeout: DispatchTime.distantFuture)
        }
    }
    
    func getParam(key: String) -> Any?
    {
        //return _mainParams[key] ?? MobClick.getConfigParams(key) ?? _presetParams[key]
        return _mainParams[key] ?? _presetParams[key]
    }
    
    private func loadPresetConfig()
    {
        if let url = Bundle.main.url(forResource: "config", withExtension: "json"),
           let data = try? Data(contentsOf: url),
           let obj = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
        {
            if let param = obj as? [AnyHashable:Any]
            {
                _presetParams = param
            }
        }
        
        loadCachedConfig()
    }
    
    private func loadCachedConfig()
    {
        //如果没有本地缓存，则从预设配置中拷贝一份
        loadRemoteConfig(cachedVersion: "0")
    }
    
    //从线上加载缓存
    private func loadRemoteConfig(cachedVersion:String)
    {
        
    }
    
    private func parseConfigData()
    {
        
    }
    
    //路由表
    private func loadOpenURLMapList()
    {
        /**
        if let path = NSBundle.mainBundle().pathForResource("url_map_list", ofType: "json"),
           let data = NSData(contentsOfFile: path)
        {
            let json = JSON(data)
            trace(json)
            
            if let list = SWGetURLMapListRsp.yy_modelWithJSON(data)?.list
            {
                let validList:[SWRouterMapItem] = list.flatMap({SWRouterMapItem(nativeURL: $0.native, regexPattern: $0.origin)})
                if validList.count > 0
                {
                    SWRouter.MapList += validList
                }
            }//end list
        }//if data
         **/
    }
    
    private func mainThreadResume()
    {
        if !_mainThreadResumed
        {
            _mainThreadResumed = true
            semaphore.signal()
        }
    }
    
    //因为Token有效期很短，需要在启动时检查token是否过期
    private func tokenAvailabilityCheck()
    {
        SWAccountManager.sharedManager().tokenAvailabilityCheck(successCallback: {[weak self] in
            self?.mainThreadResume()
        }, failCallback: {[weak self] error in
            self?.mainThreadResume()
        })
    }
    
    private func getLaunchADInfo()
    {
        
    }
    
    @objc private func UMOnlineConfigFinish()
    {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SWConfigManagerConfigChangedNotification), object: nil)
    }
    
}
